from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from sklearn.cluster import DBSCAN
import numpy as np

# 生成数据
X, y = make_blobs(n_samples=300,  # 样本数量
                  centers=4,  # 聚类中心数量
                  random_state=np.random.randint(1, 1000))  # 随机种子

# 创建 DBSCAN 模型
dbscan = DBSCAN(eps=1, min_samples=5)  # 调整 eps 和 min_samples 参数

# 拟合数据
labels = dbscan.fit_predict(X)

# 输出聚类结果
print("Estimated number of clusters:", len(set(labels)) - (1 if -1 in labels else 0))
print("Estimated number of noise points:", list(labels).count(-1))

plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis', edgecolors='k')
plt.title("DBSCAN Clustering Result")
plt.show()